<template>
  <div>
    <el-dialog
      :title="form.id ? '修改部门' : '新增部门'"
      :visible.sync="visible"
      width="70%"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="门店名称" label-width="120px">
          <div style="width: 70%;">
            <el-input v-model="form.companyName" disabled size="small" />
          </div>
        </el-form-item>
        <el-form-item label="部门名称" prop="name" :rules="{ required: true, message: '部门名称不能为空'}" label-width="120px">
          <div style="width: 70%;">
            <el-input v-model="form.name" placeholder="请输入部门名称" clearable size="small" />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button :loading="loading" type="primary" @click="onSubmit">{{ form.id ? '立即修改' : '立即创建' }}</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    defaultValue: {
      type: Object,
      default: () => ({})
    },
    id: Number
  },
  data() {
    return {
      form: {},
      tableData: [],
      searchFormData: {},
      loading: false
    }
  },
  watch: {
    defaultValue(val, val2) {
      this.form = val
    }
  },

  methods: {
    handleClose() {
      this.$emit('close')
    },

    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const p = {
            name: this.form.name,
            companyId: this.form.companyId
          }
          this.form.id && (p['id'] = this.form.id)
          this.request(p)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    async request(params) {
      try {
        this.loading = true
        await request({
          url: params.id ? 'system/company-dept/update' : 'system/company-dept/add',
          method: 'post',
          data: params
        })
        this.$message({
          message: params.id ? '修改成功' : '添加成功',
          type: 'success',
          duration: 2000,
          onClose: () => {
            this.$emit('add-success')
            this.$refs['form'].resetFields()
          }
        })
      } catch (error) {
        this.$message({
          message: error,
          type: 'warning'
        })
      } finally {
        this.loading = false
      }
      //
    }
  }
}
</script>
